function pw = derivative(w, p)
% Calculate the derivative of p with respect to w, where both w and p are
% vectors of the same length. w is a monotone sequence.  
N = numel(w);
p_left = p( 1:(N-2) );   p_right=p(3:N);  p_middle=p(2:(N-1));   
w_left = w( 1:(N-2) );    w_right=w(3:N);   w_middle=w(2:(N-1)); 
pw = zeros(N,1);
pw( 2:(N-1) ) = (w_right - w_middle)./(w_right-w_left).*( p_middle - p_left )./(w_middle - w_left) + (w_middle - w_left)./(w_right-w_left).*( p_right - p_middle  )./(w_right - w_middle);
pw(1) = ( p(2) - p(1) ) / ( w(2) - w(1) );
pw(N) = ( p(N) - p(N-1) ) / ( w(N) - w(N-1) );